<template>
	<!-- 标题输入框 -->
	<div
		class="ly-input w-full border-b border-b-blue-300"
		:style="{ height: `${height}px` }">
		<input
			:type="type"
			v-model="inputValue"
			ref="ly-input"
			:placeholder="placeholder"
			:style="{ fontSize: `${fontSize}px` }"
			class="w-full h-full text-blue-500"
			:class="{ 'font-bold': bold }" />
		<div class="line flex items-center justify-center">
			<div class="l" :style="{ width: isFoucs ? '100%' : '0' }"></div>
		</div>
	</div>
</template>

<script lang="ts">
export default defineComponent({
	name: 'LyInput',
	props: {
		type: {
			type: String,
			default: 'text',
		},
		placeholder: {
			type: String,
			default: '请输入笔记标题',
		},
		modelValue: {
			type: String,
			required: true,
		},
		fontSize: {
			type: Number,
			default: 16,
		},
		bold: {
			type: Boolean,
			default: false,
		},
		height: {
			type: Number,
			default: 12,
		},
	},
	emits: ['update:modelValue'],
	setup(props, { emit }) {
		// 输入框值 - 双向绑定
		const inputValue = ref<string>(props.modelValue);
		watch(inputValue, (val: string) => {
			emit('update:modelValue', val);
		});
		watch(
			() => props.modelValue,
			(val: string) => {
				inputValue.value = val;
			}
		);

		// 输入框焦点状态
		const isFoucs = ref<boolean>(false);
		const lyInput = useTemplateRef<HTMLInputElement>('ly-input');

		onMounted(() => {
			lyInput.value?.addEventListener('focus', () => {
				isFoucs.value = true;
			});

			lyInput.value?.addEventListener('blur', () => {
				isFoucs.value = false;
			});
		});

		return {
			isFoucs,
			inputValue,
		};
	},
});
</script>

<style lang="scss" scoped>
.ly-input {
	position: relative;
	box-sizing: border-box;

	input {
		outline: none;
		border: none;
	}

	.line {
		bottom: 0;
		width: 100%;
		height: 2px;
		position: absolute;

		.l {
			width: 0;
			height: 100%;
			transition: width 0.2s;
			background-color: #2b7fff;
		}
	}
}
</style>
